package cn.itcast.consumer.web;

import cn.itcast.consumer.client.UserClient;
import cn.itcast.consumer.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 虎哥
 */
@RestController
@RequestMapping("consumer")
//@DefaultProperties(defaultFallback = "defaultFallback")
public class ConsumerController {

    @Autowired
    private UserClient userClient;

    @GetMapping("{id}")
    public User queryUserById(@PathVariable("id") Long id) {
        return userClient.queryUserById(id);
    }

//    @Autowired
//    private RestTemplate restTemplate;
//    @HystrixCommand(commandProperties = {
//            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
//            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000")
//    })
    /*@HystrixCommand
    @GetMapping("{id}")
    public String queryUserById(@PathVariable("id") Long id) {
        if(id % 2 == 0){
            throw new RuntimeException();
        }
        // 以服务的名称代替服务的ip和端口
        String url = String.format("http://user-service/user/%d", id);
        return restTemplate.getForObject(url, String.class);
    }*/

    public String defaultFallback() {
        return "别挤了，服务器要炸了!";
    }

    /*// 手动拉取
    @Autowired
    private DiscoveryClient discoveryClient;

//    int count = 0;

    @GetMapping("{id}")
    public User queryUserById(@PathVariable("id") Long id) {
        // 拉取服务列表
        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        // 利用负载均衡算法，从多个实例列表中，选择一个， 随机负载均衡
        int index = new Random().nextInt(instances.size());

//        count = (count + 1) % instances.size();
//        ServiceInstance instance = instances.get(count);

        ServiceInstance instance = instances.get(index);
        String host = instance.getHost();
        int port = instance.getPort();
        // 准备url
        String url = String.format("http://%s:%d/user/%d", host, port, id);
        return restTemplate.getForObject(url, User.class);
    }*/
}
